class User < ActiveRecord::Base

  attr_accessible :address, :email, :fullname, :idnumber, :last_sign_in_at, :password, :phone, :role
  attr_accessible :password_confirmation

  validates :password, :confirmation => true,
                       :length => { :minimum => 8 }
  validates :email, :uniqueness => true ,:format => { :with => /^([^@\s]+)@((?:[-a-z0-9]+.)+[a-z]{2,})$/i }
  before_save :encrypt_password


  def self.authenticate(login_email="", login_password="")
    user = User.find_by_email(login_email)
    if user && user.match_password(login_password)
      return user
    else
      return false
    end
  end

  def match_password(login_password="")
    password.eql? encrypt(login_password)
  end
  
  
  def encrypt_password()
      self.password = encrypt(self.password)
  end
  
  def encrypt(string_To_Encrypt="")
      return Digest::MD5.hexdigest(string_To_Encrypt)
  end
  
  def reset_password()
    new_password = random_string(8)
    return new_password
  end
    
  def random_string(len)
    chars = ("a".."z").to_a + ("A".."Z").to_a + ("0".."9").to_a
    newpass = ""
    1.upto(len) { |i| newpass << chars[rand(chars.size-1)] }
    return newpass
  end
  
end
